package com.study.concurrency;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierTest {

	//CyclicBarrier 可重用
	public static void main(String[] args) {
		CyclicBarrier cyclicBarrier = new CyclicBarrier(2); //两个一组开始接着工作
		for(int i=0; i <4; i++){
			new Worker(cyclicBarrier).start();
		}
	}
}

class Worker extends Thread{
	
	private CyclicBarrier cyclicBarrier;

	public Worker(CyclicBarrier cyclicBarrier) {
		super();
		this.cyclicBarrier = cyclicBarrier;
	}
	
	public void run(){
		System.out.println(Thread.currentThread().getName()+"开始等待其他线程");
		try {
			this.cyclicBarrier.await();
			System.out.println(Thread.currentThread().getName()+"开始接着工作");
			TimeUnit.SECONDS.sleep(new Random().nextInt(5));
			System.out.println(Thread.currentThread().getName()+"工作完成。");
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}